// pages/orderDetail/orderDetail.js
import {
  unified_order,
  unified_order_v4
} from '../../utils/api.js'
import {
  MD5
} from '../../utils/MD5.js'

var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    items: [],
    addr: {},
    orderInfo: {},
    goodsInfo: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  // 复制到剪贴版
  copyToCli: function(e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.content,
      success(res) {
        app.showTipMsg('复制到剪贴板')
      }
    })
  },
  onLoad: function(options) {
    var id = options.id;
    var that = this;
    var url2 = '/order/details';
    var params2 = {
      id: id
    };
    app.HttpPostSend(url2, params2, function(res) {
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
      } else {
        if (res.data) {
          var orderInfo = res.data.orderInfo;

          var goodsInfo = res.data.goodsInfo;
          for (var i = 0; i < goodsInfo.length; i++) {
            goodsInfo[i].title = goodsInfo[i].title.slice(0, 12);
          }

          that.setData({
            orderInfo: orderInfo,
            goodsInfo: goodsInfo,
            spec_price_name: res.data.spec_price_name
          })
        }
      }
    });
  },
  //点击进入详情页面
  bindGoodsTap: function(e) {
    var id = e.detail.button_typId;
    var title = e.detail.button_status;
    wx.navigateTo({
      url: '../goodsDetail/goodsDetail?id=' + id + '&title=' + title,
    })
  },

  bindEditTap: function(e) {
    wx.navigateTo({
      url: '../myAddress/myAddress?goodsId=' + this.data.goodsId + '&mount=' + this.data.mount,
    })
  },
  // 退换
  bindtuih: function(e) {
    if (e.currentTarget.dataset.refund_status == -1) {
      if (this.data.orderInfo.spell_status > 0){
        wx.showModal({
          title: '提示',
          content: '拼团活动未结束暂不能退换货',
          showCancel:false,
          success:function(){}
        })
      }else{
        wx.redirectTo({
          url: '../../shopPages/Replacement/Replace?order_id=' + e.currentTarget.dataset.order_id + "&goods_id=" + e.currentTarget.dataset.goods_id
        })
      }
      
    }

  },
  //点击提醒发货
  tishiSent: function(e) {
    var id = e.currentTarget.dataset.id;
    var mgid = e.currentTarget.dataset.mgid;
    var order_group_id = e.currentTarget.dataset.order_group_id;
    app.showTipMsg('已提醒!');
    // 发送模板消息-访客到访通知
    app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 9, '', '', order_group_id, '', '', mgid);
  },
  //点击查看订单详情
  showOrder: function(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/orderDetail/orderDetail?id=' + id,
    })
  },
  showExpress: function(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/shopPages/express/express?id=' + id,
    })
  },
  //点击付款
  payOrder: function(e) {
    var id = e.currentTarget.dataset.id;
    var sn = e.currentTarget.dataset.sn;
    var freight_free = e.currentTarget.dataset.freight_free;
    var price = e.currentTarget.dataset.price;
    var integral_price = e.currentTarget.dataset.integral_price;
    var mgid = e.currentTarget.dataset.mgid;
    // const title = e.currentTarget.dataset.title;
    let params = {
      total_fee: price * 100,
      openid: app.globalData.openid,
      order_id: id + '',
      // body: title,
      body: 'pay_order',
      type: 1,
      order_source: 1,
      timestamp: new Date().getTime(),
    }
    params.sign = app.getSign(params)
    try {
      app.HttpPostSend(unified_order_v4, params, function(unified_order_res) {
        if (unified_order_res.msg != "success") {
          wx.showModal({
            title: '提示',
            content: unified_order_res.msg,
            showCancel: false,
            success:function(){
              wx.switchTab({
                url: '/pages/shop/shop',
              })
            }
          })
        } else {
          // console.log(unified_order_res)
          if (Number(unified_order_res.code) == 1) {
            // let order_arr = unified_order_res.data.order_arr
            // 数据结构改变 let order_arr = unified_order_res.data
            
            let order_arr = unified_order_res.data
            if (unified_order_res.data.order_arr != undefined) {
              order_arr = unified_order_res.data.order_arr
            }
            let signA = "appId=" + order_arr.appid + "&nonceStr=" + order_arr.noncestr + "&package=prepay_id=" + order_arr.prepayid + "&signType=MD5&timeStamp=" + order_arr.timestamp;
            let signB = signA + "&key=" + unified_order_res.data.key
            let new_pay_sign = MD5(signB)
            // console.log(new_pay_sign)
            wx.requestPayment({
              timeStamp: order_arr.timestamp,
              nonceStr: order_arr.noncestr,
              package: 'prepay_id=' + order_arr.prepayid,
              signType: 'MD5',
              profit_sharing: 'Y',
              paySign: new_pay_sign,
              success(pay_res) {
                // console.log(pay_res)
                var url2 = '/order/updateOrderStatus_v4';
                var params2 = {
                  id: id,
                  type: 2,
                  invite_id: app.globalData.shareOptions.share_id,
                  invite_uid: app.globalData.shareOptions.carte_id,
                  timestamp: new Date().getTime(),
                };
                params2.sign = app.getSign(params2)
                app.HttpPostSend(url2, params2, function(res) {
                  if (res.msg != "success") {
                    app.showTipMsg(res.msg);
                  } else {

                    // 雷达添加查看记录 -商品付款成功数
                    app.radarAdd(app.globalData.SwitchTabParams.v_id, 19, 0, price, app.globalData.userInfo.logo)

                    // 发送模板消息-访客到访通知
                    // app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 1, '/radarPages/radarCenter/radarCenter', '付款成功', '', '', '')

                    // 发送模板消息-访客到访通知
                    app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 10, '/shopPages/houOrderDetail/houOrderDetail?id=' + id, '', sn, '', '', mgid);

                    wx.redirectTo({
                      url: '/shopPages/orderSuccess/orderSuccess?price=' + price + '&id=' + id + '&integral=' + JSON.stringify(integral_price) + '&freight_free=' + freight_free
                    })
                  }
                });
              },
              fail(err_res) {
                // console.log(err_res)
                wx.redirectTo({
                  url: '/pages/myOrders/myOrders',
                })
              }
            })
          } else {
            app.showTipMsg(res.msg);
          }
          // wx.navigateTo({
          //   url: '/pages/paySuccess/paySuccess?price=' + that.data.sumprice + '&id=' + res.data
          // })
        }
      })
    } catch (error) {
      console.log(error)
    }
  },
  //点击取消订单
  cancelOrder: function(e) {
    wx.showModal({
      title: '提示',
      content: '确定要删除订单?',
      success(res) {
        if (res.confirm) {
          var id = e.currentTarget.dataset.id;
          var url2 = '/order/updateOrderStatus_v4';
          var params2 = {
            id: id,
            type: 0,
            invite_id: app.globalData.shareOptions.share_id,
            invite_uid: app.globalData.shareOptions.carte_id,
            timestamp: new Date().getTime(),
          };
          params2.sign = app.getSign(params2)
          app.HttpPostSend(url2, params2, function(res) {
            if (res.msg != "success") {
              app.showTipMsg(res.msg);
            } else {

              // 雷达添加查看记录 -取消订单数
              app.radarAdd(app.globalData.SwitchTabParams.v_id, 20, '', '', app.globalData.userInfo.logo)

              // 发送模板消息-访客到访通知
              // app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 1, '/radarPages/radarCenter/radarCenter', '取消了订单', '', '', '')

              wx.redirectTo({
                url: '/pages/myOrders/myOrders'
              })
            }
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //点击确认收货
  sureGet: function(e) {
    wx.showModal({
      title: '提示',
      content: '确认收货吗?',
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '收货中',
          })
          var id = e.currentTarget.dataset.id;
          var url2 = '/order/updateOrderStatus_v4';
          var params2 = {
            id: id,
            type: 4,
            invite_id: app.globalData.shareOptions.share_id,
            invite_uid: app.globalData.shareOptions.carte_id,
            timestamp: new Date().getTime(),
          };
          params2.sign = app.getSign(params2)
          app.HttpPostSend(url2, params2, function(res) {
            wx.hideLoading();
            if (res.msg != "success") {
              app.showTipMsg(res.msg);
            } else {

              // 发送模板消息-确认收货通知
              // app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 6, '/radarPages/radarCenter/radarCenter', id, '', '', '')
              wx.redirectTo({
                url: '/pages/myOrders/myOrders'
              })
            }
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  //点击去评价
  pingjOrder: function(e) {
    var id = e.currentTarget.dataset.id;
    wx.redirectTo({
      url: '/shopPages/Publication/Publication?order_id=' + id,
    })
  },
  //点击删除订单
  deleteOrder: function(e) {
    var id = e.currentTarget.dataset.id;
    var url2 = '/order/updateOrderStatus_v4';
    var params2 = {
      id: id,
      type: 7,
      invite_id: app.globalData.shareOptions.share_id,
      invite_uid: app.globalData.shareOptions.carte_id,
      timestamp: new Date().getTime(),
    };
    params2.sign = app.getSign(params2)
    app.HttpPostSend(url2, params2, function(res) {
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
      } else {
        wx.navigateTo({
          url: '/pages/myOrders/myOrders'
        })
      }
    });
  },
  //点击申请售后
  applyGoods: function(e) {
    wx.showModal({
      title: '提示',
      content: '请确认该订单申请售后',
      success(res) {
        if (res.confirm) {
          var id = e.currentTarget.dataset.id;
          var url2 = '/order/updateOrderStatus_v4';
          var params2 = {
            id: id,
            type: 6,
            invite_id: app.globalData.shareOptions.share_id,
            invite_uid: app.globalData.shareOptions.carte_id,
            timestamp: new Date().getTime(),
          };
          params2.sign = app.getSign(params2)
          app.HttpPostSend(url2, params2, function(res) {
            if (res.msg != "success") {
              app.showTipMsg(res.msg);
            } else {
              wx.navigateTo({
                url: '/pages/myOrders/myOrders'
              })
            }
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },

  // 点击联系客服进去咨询页面
  bindGoSocksTap: function(e) {
    wx.navigateTo({
      url: '../socks/socks?mid=' + this.data.orderInfo.mg_uid
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },
  toGoodsDetail: function(e) {
    var that = this;
    if (that.data.orderInfo.spell_id > 0){
      wx.navigateTo({
        url: "/shopPages/goodsDetailSpell/goodsDetailSpell?id=" + e.currentTarget.dataset.id + "&s_id=" + this.data.orderInfo.spell_id
      })
    }else{
      wx.navigateTo({
        url: "/pages/goodsDetail/goodsDetail?id=" + e.currentTarget.dataset.id
      })
    }
    
  }

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})